# -*- coding: utf-8 -*-
#
# fusion.feed.Feed
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Harri Hämäläinen <harri.hamalainen@helsinki.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

'''
Handle URLs of the form "/feed/([0-9a-f]{40})/".
'''

import web
import time
from fusion.http.util import withdb
from fusion.feed.feedgenerator import FeedGenerator
from fusion.db.exceptions import *

class Feed(object):

    def GET(self, collection, request_path=''):
        input = web.input()
        self.GET_atom(input, collection, request_path)
        return

    @withdb
    def GET_atom(self, db, input, collection, request_path):
        TIMEOUT_TRANSFER = 2
        TIMEOUT_GET_UNKNOWN = 60
        try: 
            if db.get(collection, "info/title", block=True, timeout=TIMEOUT_GET_UNKNOWN) is None:
                return web.notfound()

        except NoSuchCollection:
            db.import_collection(collection)
            if db.get(collection, "info/title", block=True, timeout=TIMEOUT_GET_UNKNOWN) is None:
                # db.remove_collection(collection) # Is this ok? Maybe not.
                return web.notfound()
            db_last_mark = db.get_mark()
            while True: 
                time.sleep(TIMEOUT_TRANSFER)
                entries = [entry for entry in db.keys(collection, last_mark=db_last_mark) \
                          if entry[:5] == "feed/"]
                if len(entries) == 0:
                    break
                db_last_mark = db.get_mark()

        if request_path == '':
            # db, collection, create_summary, entries_path, tags_path, comments_path
            feedgen = FeedGenerator(db, collection, True, 'feed/entries/', 'feed/tags/', 'feed/comments/')
            web.header('Content-Type', 'application/atom+xml')
            out =  '<?xml version="1.0" encoding="UTF-8"?>'
            out += feedgen.get_feed()
            web.output(out)

        else:
            if db.get(collection, "feed/entries/"+request_path, block=True, timeout=TIMEOUT_GET_UNKNOWN) is None:
                return web.notfound()
            feedgen = FeedGenerator(db, collection, entries_path='feed/entries/')
            entry = feedgen.get_entry(request_path)
            if entry is None:
                return web.notfound()
            web.header('Content-Type', 'text/xml')
            out = '<?xml version="1.0" encoding="UTF-8"?>'
            out += feedgen.get_entry(request_path)
            web.output(out)
